import Vue from "vue";
import axios from "axios";
import { cookie, LoadingPlugin } from "vux";
Vue.use(LoadingPlugin);

let requestingCount = 0;

const handleRequestLoading = () => {
  if (!requestingCount) Vue.$vux.loading.show();
  requestingCount++;
};
const handleResponseLoading = () => {
  requestingCount--;
  if (!requestingCount) Vue.$vux.loading.hide();
};

// let baseURL = "http://172.17.0.42/dc-web"; //测试服务器
let baseURL = "http://119.145.168.112:51042/dc-web"; //代理测试服务器

let axiosInstance = axios.create({
  baseURL: baseURL
});
// 添加请求拦截器
axiosInstance.interceptors.request.use(
  config => {
    // 在发送请求之前将token加入http请求的header中
    // console.info("cookie--", cookie.get("userinfo"));
    // console.info("config---", config);
    let userInfo = cookie.get("userinfo");
    userInfo = userInfo ? JSON.parse(userInfo) : {};
    if (userInfo.token) config.headers["x-token"] = userInfo.token;
    handleRequestLoading();
    return config;
  },
  error => {
    // 对请求错误做些什么
    handleRequestLoading();
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    handleResponseLoading();
    return response.data;
  },
  error => {
    // 对响应错误做点什么
    handleResponseLoading();
    return Promise.reject(error);
  }
);
export default axiosInstance;
